package itsm.isperp.report.paser;

import itsm.isperp.framework.utils.DateUtils;

import java.util.ArrayList;
import java.util.List;

import org.joda.time.LocalDate;

/**
 * 
 * 
 * 
 * @author lizx
 * @date 2015-12-6
 * @since 1.0
 * 
 */
public class QueryLineByWeekPaser {

	public static QueryLineLegend paser(LocalDate startDate, LocalDate endDate,
			boolean line) {
		QueryLineLegend m = new QueryLineLegend();

		List<String> ds = new ArrayList<>();

		int lastWeek = endDate.getWeekOfWeekyear();

		int y = endDate.getYear();
		int yl = y - 1;

		LocalDate ld = endDate.withYear(endDate.getYear() - 1);
		int lLastWeek = ld.weekOfWeekyear().getMaximumValue();

		LocalDate sd;

		if (lastWeek == 3) {
			sd = ld.withWeekOfWeekyear(lLastWeek).withDayOfWeek(1);
			ds.add(yl + "-" + String.format("%02d", (lLastWeek)));
			ds.add(y + "-01");
			ds.add(y + "-02");
			ds.add(y + "-03");
		} else if (lastWeek == 2) {
			sd = ld.withWeekOfWeekyear((lLastWeek - 1)).withDayOfWeek(1);
			ds.add(yl + "-" + String.format("%02d", (lLastWeek - 1)));
			ds.add(yl + "-" + String.format("%02d", (lLastWeek)));
			ds.add(y + "-01");
			ds.add(y + "-02");
		} else if (lastWeek == 1) {
			sd = ld.withWeekOfWeekyear((lLastWeek - 2)).withDayOfWeek(1);
			ds.add(yl + "-" + String.format("%02d", (lLastWeek - 2)));
			ds.add(yl + "-" + String.format("%02d", (lLastWeek - 1)));
			ds.add(yl + "-" + String.format("%02d", (lLastWeek)));

			ds.add(y + "-01");
		} else {

			sd = endDate.withWeekOfWeekyear((lastWeek - 3)).withDayOfWeek(1);

			ds.add(y + "-" + String.format("%02d", (lastWeek - 3)));
			ds.add(y + "-" + String.format("%02d", (lastWeek - 2)));
			ds.add(y + "-" + String.format("%02d", (lastWeek - 1)));
			ds.add(y + "-" + String.format("%02d", (lastWeek)));
		}

		if (line) {

			m.setStart(DateUtils.formatDate(sd.dayOfWeek().withMinimumValue()
					.toDate()));
		} else {

			m.setStart(DateUtils.formatDate(endDate.dayOfWeek()
					.withMinimumValue().toDate()));

		}

		m.setEnd((DateUtils.formatDate(endDate.dayOfWeek().withMaximumValue()
				.toDate())));

		m.setValues(ds);

		m.setDateFormat("yyyy-iw");
		return m;
	}
}
